import { Col, Empty, Spin, Tabs } from 'antd';
import { ContractHomeContext } from '../../../common';
import _ from 'lodash';
import Cls from 'classnames';
import pageStyles from '@/common/pageLayout.less';
import ReactDOM from 'react-dom';
import * as echarts from 'echarts';
import React, { useContext, useEffect, useMemo, useRef } from 'react';
import { ContractHomePageCountAPI } from '../../../common/type';
import { handleSumStr } from '@/pages/ContractController/ContractAllCount/mconfig';

export const ContractCountCollecRight: React.FC<ContractHomePageCountAPI.IContractCountCollecRight> = ({ countLoading }) => {
  /**引入上下文 */
  const { styleFixCls, collectionData, curRes } = useContext(ContractHomeContext);
  /** 折线图Ref */
  let pieChartRef: any = useRef();
  useEffect(() => {
    renderPieChart();
  }, [collectionData]);

  const renderMemo = useMemo(() => {
    let info: any = [];
    collectionData?.forEach((item) => {
      info.push({
        searchStateName: item?.searchStateName,
        searchState: item?.searchState,
        totalNum: item?.totalNum,
        expectAllSum: item?.expectAllSum,
      });
    });
    return {
      info,
    };
  }, [collectionData]);
  const calculatePercentage = (A, B) => {
    // 避免除以零的情况
    if (A === 0) {
      return 0;
    }

    // 计算百分比
    const percentage = (B / A) * 100;

    // 保留两位小数
    return parseFloat(percentage.toFixed(2));
  };

  const renderPieChart = () => {
    if (pieChartRef?.current) {
      const putStateViewDiv: any = ReactDOM.findDOMNode(pieChartRef?.current);
      const myChart = echarts.init(putStateViewDiv);

      let option = {
        title: {
          text: `采购状态数量统计`,
          left: 'left',
        },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            let payload: Record<string, any> = {};
            if (params.seriesName == '数量') {
              payload = renderMemo?.info?.find((item: any) => item?.searchStateName == params?.name);
              return (
                params.name +
                '<br/>' +
                params.marker +
                params.seriesName +
                '：' +
                params.value +
                ` 个<br/>${params.marker}金额：` +
                handleSumStr(payload?.expectAllSum)
              );
            } else {
              payload = renderMemo?.info?.find((item: any) => item?.searchStateName == params?.name);
              return (
                params.name +
                '<br/>' +
                params.marker +
                params.seriesName +
                '：' +
                handleSumStr(params?.value) +
                `<br/>${params.marker}数量：` +
                payload?.totalNum +
                ` 个`
              );
            }
          },
        },
        legend: {
          data: renderMemo?.info?.map((item: any) => item.searchStateName),
          orient: 'vertical',
          left: 'left',
          padding: [40, 5],
        },
        series: [
          {
            name: '数量',
            type: 'pie',
            selectedMode: 'single',
            radius: [0, '30%'],
            top: '8%',
            label: {
              position: 'inner',
              fontSize: 14,
              formatter: `{c}`,
            },
            labelLine: {
              show: false,
            },
            data: renderMemo?.info?.map((item: any) => {
              return {
                name: item.searchStateName,
                value: item?.totalNum,
              };
            }),
            center: ['60%', '50%'],
          },
          {
            name: '金额',
            type: 'pie',
            radius: ['45%', '60%'],
            top: '8%',
            labelLine: {
              length: 30,
            },
            data: renderMemo?.info?.map((item: any) => {
              return {
                name: item.searchStateName,
                value: item?.expectAllSum,
              };
            }),
            label: {
              formatter: `{c}`,
            },
            center: ['60%', '50%'],
          },
        ],
      };
      myChart.setOption(option as any);
    }
  };

  /** tab配置 */
  const tabsItem = useMemo(() => {
    return [
      {
        label: '采购状态数量统计',
        key: '1',
        children: collectionData?.length ? (
          <div className={`${styleFixCls}RootDiv-echartBoxDiv`} ref={pieChartRef}></div>
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        ),
      },
    ];
  }, [curRes, collectionData?.length]);

  /*
  useEffect(() => {
    // 窗口大小变化时重新渲染图表
    const handleResize = () => {
      if (pieChartRef.current) {
        const chartInstance = echarts.getInstanceByDom(pieChartRef.current);
        if (chartInstance) {
          chartInstance.resize();
        }
        //  else {
        //   renderPieChart();
        // }
      }
    };

    // 添加窗口大小变化事件监听器
    window.addEventListener('resize', handleResize);

    // 组件卸载时移除事件监听器
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []); // 仅在组件挂载时执行一次，使用空数组作为依赖项，以确保只在组件挂载时执行一次
  */
  return (
    <Col span={8}>
      <Spin spinning={countLoading}>
        <div className={Cls(pageStyles['commonTabsLine'])} style={{ height: '100%', width: '100%' }}>
          <Tabs items={tabsItem} />
        </div>
      </Spin>
    </Col>
  );
};
